<?php
//店铺设置
namespace Store\Controller;
//use Think\Controller;
use Store\Controller\StoreController;
class StatController extends StoreController
{
    public function index(){
        $sess = session();
        $start_time = strtotime(date('Y-m'));
        $t = date('t');
        $end_time = strtotime(date('Y-m'.'-'.$t.' 23:59:59'));
        $where['finnshed_time'] = array(array('gt',$start_time),array('lt',$end_time));
        $where['store_id'] = $sess['store_id'];
        $order = D('Order')->relation('OrderGoods')->where($where)->select();
        foreach($order as $v){
            $order_res['order_amount'] += $v['order_amount']; //有效订单的总金额
            ++$order_res['order_user_num'];                        //有效订单的下单会员总数
            $order_res['user'][] = $v['buyer_id'];
            foreach($v['OrderGoods'] as $goods){
                $order_res['order_goods'] += $goods['goods_num'];                 //有效订单包含的商品总数量
            }
            $order_res['order_num'] += count($v['order_id']);  //有效订单的总数量
        }
        $this->assign('order_res',$order_res);

        //店铺关注
        $favorites = M('Favorites');
        $data['fav_time'] = array(array('gt',$start_time),array('lt',$end_time));
        $data['fav_id'] = $sess['store_id'];
        $collect = $favorites->where(array('fav_id'=>$sess['store_id']))->field("count(member_id) as collect_num")->find();
        $month_collect = $favorites->where($data)->field("count(member_id) as collect_num")->find();
        $this->assign('collect',$collect);
        $this->assign('month_collect',$month_collect);

        //当月下单量折线图
        $order = M('order');
        $o = $order->where($where)->group('FROM_UNIXTIME(add_time,"%d")')->field('FROM_UNIXTIME(add_time,"%d") as add_time ,count(order_id) as num')->order('add_time desc')->select();
        $same_month = $this->line($o,'add_time','num',$t);
        $this->assign('same_month',$same_month);

        $this->display();
    }


    //转换折线数据
    //$arr 要处理的数组
    //$day 处理数据当月的天数
    //返回一个下表为‘shuju’每天的量的字符串，和‘day’下标的每天的字符串
    protected function line($arr,$field1,$field2,$day){
        $a = array();
        $b = array();
        if(empty($arr)){
            for($i = 1;$i<=$day;$i++){
                $b['shuju'] .= '0,';
                $b['day'] .= $i.',';
            }
            $b['shuju'] = rtrim($b['shuju'],',');
        }else{
            for($i = 1;$i<=$day;$i++){
                $a[$i] = 0;
                $b['day'] .= $i.',';
            }
            foreach($a as $k=>$v){
                foreach($arr as $v1){
                    if($k == $v1[$field1]){
                        $a[$k] = $v1[$field2];
                    }
                }
            }
            $b['shuju'] = implode(',',$a);
        }
        $b['day'] = rtrim($b['day'],',');
        return $b;
    }
}